var mongoose = require('mongoose')
    , User = mongoose.model('User')
    , crypto = require('crypto')
/* 

/*
 * GET users listing.
 */

// exports.list = function(req, res){
//   res.send("respond with a resource");
// };

//signup
exports.signup = function(req, res){
  res.render('signup', { 
  	title: '注册',
    user: req.session.user,
  	success: req.flash('success').toString(),
  	error: req.flash('error').toString()
  });
};
exports.create = function(req, res){
    var password = req.body.password
   	    , confirm_password = req.body.confirm_password;
   	if (password != confirm_password) {
   		req.flash('error', '两次输入的密码不一致!');
   		return res.redirect('/signup');
   	}
   	User.loadByOp({username: req.body.username}, function(err, user){
   		if (err) {
   			req.flash('error', err);
   			return res.redirect('/signup');
   		}
   		if (user) {
   			req.flash('error', '用户已存在!');
   			return res.redirect('/signup');
   		}
   		var user = new User();
	   	user.username = req.body.username;
	   	user.password = password;
	   	user.email = req.body.email;
      user.provider = 'local';
      user.avatar = 'http://www.gravatar.com/avatar/' + md5(req.body.email.toLowerCase()) + '?s=48'
	   	user.save(function(err){
	   		if (err) {
	   			req.flash('error', err);
	   			return redirect('signup');
	   		}
	   		req.session.user = user;
	   		req.flash('success', '注册成功!');
	   		res.redirect('/');
	   	});

   	});
   	



};

//signin
exports.signin = function(req, res){
  res.render('signin', { 
    title: '登录',
    user: req.session.user,
    success: req.flash('success').toString(),
    error: req.flash('error').toString()
  });
};
exports.login = function(req, res){
    User.loadByOp({username: req.body.username}, function(err, user){
        if (err) {
          req.flash('error', err);
          return res.redirect('/signin');
        }
        if (!user) {
          req.flash('error', '用户不存在！');
          return res.redirect('/signin');
        }
        var password = md5(req.body.password);
        if (password != user.hashed_password) {
          req.flash('error', '密码错误！');
          return res.redirect('/signin');
        }
        req.session.user = user;
        req.flash('success', '登录成功！');
        res.redirect('/');
    });
};

//signout
exports.signout = function(req, res){
    req.session.user = null;
    req.flash('success', '登出成功!');
    res.redirect('/');
};

//auth github
exports.authCallback = function(req, res){
    //console.log(req.user);
    req.session.user = req.user;
    res.redirect('/');

}


function md5(str) {
  var md5sum = crypto.createHash('md5');
  md5sum.update(str);
  str = md5sum.digest('hex');
  return str;
}
